package com.joint.web.action.finance;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.TaskRecordService;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.finance.AuditAnswer;
import com.joint.core.entity.finance.AuditNotice;
import com.joint.core.service.AuditAnswerService;
import com.joint.core.service.AuditNoticeService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/3/15.
 */
@ParentPackage("finance")
public class AjaxAuditanswerAction extends BaseFlowAction {
    @Resource
    private AuditAnswerService auditAnswerService;
    @Resource
    private AuditNoticeService auditNoticeService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private UsersService usersService;
    @Resource
    private TaskRecordService taskRecordService;

    private String auditId;
    private AuditAnswer auditAnswer;
    private AuditNotice auditNotice;
    private Users loginUser;
    private String step;
    private int numStatus;
    private String fileId;
    private String fileIds;
    private String remarks;
    private int auditType;
    private String auditTypeText;
    private String width;

    public String execute(){
        return "auditanswer";
    }

    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        AuditNotice auditNotice=auditNoticeService.get(auditId);

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state", BaseEnum.StateEnum.Enable);
        params.put("auditNotice",auditNotice);
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny,FlowEnum.ProcessState.Draft});
        pager=auditAnswerService.findByPagerAndLimit(true, "auditanswer", pager, params);
        List<AuditAnswer> auditAnswerList;
        if (pager.getTotalCount() > 0){
            auditAnswerList = (List<AuditAnswer>) pager.getList();
        }else{
            auditAnswerList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(AuditAnswer auditAnswer:auditAnswerList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",auditAnswer.getId());
            rMap.put("createDate", DataUtil.DateToString(auditAnswer.getCreateDate(), "yyyy-MM-dd"));
            rMap.put("creater",auditAnswer.getCreater()==null?"":auditAnswer.getCreater().getName());
            rMap.put("state", auditAnswer.getProcessState().value());
            if(auditAnswer.getAuditType()==1){
                rMap.put("type","审计计划");
            }else if(auditAnswer.getAuditType()==2){
                rMap.put("type","审计结果");
            }else{
                rMap.put("type","未知");
            }
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String listAnswer(){
        if(StringUtils.isNotEmpty(auditId)){
            auditNotice=auditNoticeService.get(auditId);
//            auditAnswer=auditNotice.getAuditAnswer();
        }
        return "listAnswer";
    }

    public String input(){
        if(StringUtils.isNotEmpty(auditId)){
            System.out.println(auditId);
            auditNotice=auditNoticeService.get(auditId);
            if(StringUtils.isNotEmpty(keyId)){
                auditAnswer=auditAnswerService.get(keyId);
                fileId="";
                if(auditAnswer.getFile()!=null&&auditAnswer.getFile().size()>0){
                    for(FileManage file:auditAnswer.getFile()){
                        fileId+=file.getId()+",";
                    }
                }
            }
        }
        return "input";
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            auditAnswer=auditAnswerService.get(keyId);
            if(auditAnswer.getAuditType()==1){
                auditTypeText="审计计划";
            }else if(auditAnswer.getAuditType()==2){
                auditTypeText="审计结果";
            }
            fileId="";
            if(auditAnswer.getFile()!=null&&auditAnswer.getFile().size()>0){
                for(FileManage file:auditAnswer.getFile()){
                    fileId+=file.getId()+",";
                }
            }
        }
        return "read";
    }

    public void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            auditAnswer=auditAnswerService.get(keyId);
        }else{
            auditAnswer=new AuditAnswer();
            auditAnswer.setCreater(usersService.getLoginInfo());
        }
        auditAnswer.setCompany(usersService.getLoginInfo().getCompany());
        auditAnswer.setAuditType(auditType);
        auditAnswer.setAuditNotice(auditNoticeService.get(auditId));
        auditAnswer.setRemarks(remarks);
        List<FileManage> fileList= Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String file:fileIds.split(",")){
                fileList.add(fileManageService.get(file.trim()));
            }
        }
        auditAnswer.setFile(fileList);
    }

    public String save(){
        if(auditType==0){
            return ajaxHtmlCallback("400", "请选择审计类型！", "操作状态");
        }
        setData();
        String type="";
        if(auditType==1){
            type="审计计划";
        }else if(auditType==2){
            type="审计结果";
        }
        AuditNotice auditNotice=auditNoticeService.get(auditId);
        List<AuditAnswer> aaList3=auditNotice.getAuditAnswerList();
        for(AuditAnswer aa:aaList3){
            if(aa.getId().equals(keyId)){
                continue;
            }
            if(aa.getAuditType()==auditType){
                return ajaxHtmlCallback("400", "该审计已存在"+type+"答复类型了！", "操作状态");
            }
        }
        try {
            if(StringUtils.isNotEmpty(keyId)){
                auditAnswerService.update(auditAnswer);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                auditAnswerService.save(auditAnswer, "auditanswer", various);
                List<AuditAnswer> aaList=Lists.newArrayList();
                List<AuditAnswer> oldList=auditNotice.getAuditAnswerList();
                if(oldList!=null&&oldList.size()>0){
                    for(AuditAnswer aa:oldList){
                        aaList.add(aa);
                    }
                }
                aaList.add(auditAnswer);
                auditNotice=auditNoticeService.get(auditId);
                auditNotice.setAuditAnswerList(aaList);
                auditNoticeService.update(auditNotice);
            }

        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    public String commit(){
        setData();
        String type="";
        if(auditType==1){
            type="审计计划";
        }else if(auditType==2){
            type="审计结果";
        }
        AuditNotice auditNotice=auditNoticeService.get(auditId);
        List<AuditAnswer> aaList=auditNotice.getAuditAnswerList();
        for(AuditAnswer aa:aaList){
            if(aa.getId().equals(keyId)){
                continue;
            }
            if(aa.getAuditType()==auditType){
                return ajaxHtmlCallback("400", "该审计已存在"+type+"答复类型了！", "操作状态");
            }
        }
        Map<String,Object> var1=new HashMap<String,Object>();
        var1.put("numStatus",0);
        var1.put("curDutyId",curDutyId);
        var1.put("initDutyId",curDutyId);
        Map<String,Object> var2=new HashMap<String,Object>();
        var2.put("numStatus",1);
        var2.put("curDutyId",curDutyId);
        var2.put("initDutyId",curDutyId);

        List<String> list=Lists.newArrayList();
        List<Department> deptList=departmentService.getDepartments("产业中心");
        for(Department dept:deptList){
            Set<Power> powers=dept.getPowerSet();
            for(Power power:powers){
                if(power.getPost().getName().equals("书记")||power.getPost().getName().equals("主任")){
                    List<Users> usersList=dutyService.getPersons(dept,power.getPost());
                    for(Users user:usersList){
                        list.add(user.getId().trim());
                    }
                }
            }
        }
        var2.put("approvers",list);
        try{
            if(StringUtils.isNotEmpty(keyId)){
                auditAnswerService.approve(auditAnswer,FlowEnum.ProcessState.Running,var2,curDutyId,comment);
            }else{
                keyId=auditAnswerService.commit(auditAnswer,"auditanswer",var1,var2,curDutyId);
                List<AuditAnswer> aaList2=Lists.newArrayList();
                List<AuditAnswer> oldList=auditNotice.getAuditAnswerList();
                if(oldList!=null&&oldList.size()>0){
                    for(AuditAnswer aa:oldList){
                        aaList2.add(aa);
                    }
                }
                aaList2.add(auditAnswer);
                auditNotice.setAuditAnswerList(aaList2);
            }
            auditNotice.setStep("5");
            auditNoticeService.update(auditNotice);
        }catch (DutyNotExistsException e){
            return ajaxHtmlCallback("404","当前人员无新建权限，请联系管理员！","操作状态");
        }catch (PcfgNotExistException e){
            return ajaxHtmlCallback("404","找不到流程节点配置，请联系管理员！","操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve1(){
        auditAnswer = auditAnswerService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                auditAnswerService.approve(auditAnswer, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
            Task overtask = workflowService.getCurrentTask(keyId);
            //LogUtil.info("overtask:"+overtask);
            //会签后没有流程将对象状态设为归档
            if(overtask==null){
                AuditAnswer auditAnswer = auditAnswerService.get(keyId);
                auditAnswer.setProcessState(FlowEnum.ProcessState.Finished);
                auditAnswerService.update(auditAnswer);
                List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(auditAnswer.getId());
                for(TaskRecord taskRecord:taskRecords){
                    taskRecord.setType(2);
                    taskRecordService.update(taskRecord);
                }
            }else {
                if (runtimeService.getVariable(overtask.getExecutionId(), "nrOfCompletedInstances") == null) {
                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 2);
                }
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve2(){
        auditAnswer = auditAnswerService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        if(com.joint.base.util.StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                auditAnswerService.approve(auditAnswer, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
            Task overtask = workflowService.getCurrentTask(keyId);
            //LogUtil.info("overtask:"+overtask);
            //会签后没有流程将对象状态设为归档
            if(overtask==null){
                AuditAnswer auditAnswer = auditAnswerService.get(keyId);
                auditAnswer.setProcessState(FlowEnum.ProcessState.Finished);
                auditAnswerService.update(auditAnswer);
                List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(auditAnswer.getId());
                for(TaskRecord taskRecord:taskRecords){
                    taskRecord.setType(2);
                    taskRecordService.update(taskRecord);
                }
            }else {
                if (runtimeService.getVariable(overtask.getExecutionId(), "nrOfCompletedInstances") == null) {
                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 3);
                }
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            auditAnswer = auditAnswerService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("auditanswer");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            LogUtil.info("numStatus:" + numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            auditAnswerService.reject(auditAnswer, key, numStatus, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            auditAnswer = auditAnswerService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("auditanswer");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:" + key);
            if(com.joint.base.util.StringUtils.isEmpty(comment)){
                comment="";
            }
            auditAnswerService.deny(auditAnswer, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }



    public String getAuditId() {
        return auditId;
    }

    public void setAuditId(String auditId) {
        this.auditId = auditId;
    }

    public AuditAnswer getAuditAnswer() {
        return auditAnswer;
    }

    public void setAuditAnswer(AuditAnswer auditAnswer) {
        this.auditAnswer = auditAnswer;
    }

    public AuditNotice getAuditNotice() {
        return auditNotice;
    }

    public void setAuditNotice(AuditNotice auditNotice) {
        this.auditNotice = auditNotice;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getStep() {
        return step;
    }

    public void setStep(String step) {
        this.step = step;
    }

    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public String getFileIds() {
        return fileIds;
    }

    public void setFileIds(String fileIds) {
        this.fileIds = fileIds;
    }

    public String getRemarks() {
        return remarks;
    }

    public void setRemarks(String remarks) {
        this.remarks = remarks;
    }

    public int getAuditType() {
        return auditType;
    }

    public void setAuditType(int auditType) {
        this.auditType = auditType;
    }

    public String getWidth() {
        return width;
    }

    public void setWidth(String width) {
        this.width = width;
    }

    public String getAuditTypeText() {
        return auditTypeText;
    }

    public void setAuditTypeText(String auditTypeText) {
        this.auditTypeText = auditTypeText;
    }
}
